import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ViewPageService } from "./view-page.service";
import { AppPaginationComponent, PaginationModel } from "app/widgets/pagination/pagination.component";
import { environment } from 'environments/environment';
import { ViewComponent } from "../../../modal/view/view.component";
import { FlowComponent } from "../../../modal/flow/flow.component";
import { SingleComponent } from "../../../modal/single/single.component";
import { HistoryComponent } from "../../../modal/history/history.component";
import { ReadComponent } from "../../../modal/read/read.component";
import { QueryComponent } from "../../../modal/query/query.component";
import { ViewReadPageComponent } from "../../view/view-read-page/view-read-page.component";
import { InvestService } from "../../../invest.service";
import { DataService } from 'app/services/data.service';
import { Util } from 'app/common/util';
import * as _ from 'lodash';
import { TableComponent } from "../../../modal/table/table.component";


@Component({
  selector: 'app-view-page',
  templateUrl: './view-page.component.html',
  styleUrls: ['./view-page.component.scss'],
  providers: [ViewPageService]
})
export class ViewPageComponent implements OnInit {
  // 搜索模版
  @ViewChild("query", { read: ViewContainerRef })
  query: ViewContainerRef;
  queryComponent: ComponentRef<QueryComponent>;
  // 查看模版
  @ViewChild("view", { read: ViewContainerRef })
  view: ViewContainerRef;
  viewComponent: ComponentRef<ViewComponent>;
  // 查看流程状态模版
  @ViewChild("flow", { read: ViewContainerRef })
  flow: ViewContainerRef;
  flowComponent: ComponentRef<FlowComponent>;
  // 查看单条基金变更模版
  @ViewChild("single", { read: ViewContainerRef })
  single: ViewContainerRef;
  singleComponent: ComponentRef<SingleComponent>;
  // 查看历史变更模版
  @ViewChild("history", { read: ViewContainerRef })
  history: ViewContainerRef;
  historyComponent: ComponentRef<HistoryComponent>;
  // 阅读须知模版
  @ViewChild("viewReadPage", { read: ViewContainerRef })
  viewReadPage: ViewContainerRef;
  viewReadPageComponent: ComponentRef<ViewReadPageComponent>;
  // 模版
  @ViewChild("viewTable", { read: ViewContainerRef })
  viewTable: ViewContainerRef;
  viewTableComponent: ComponentRef<TableComponent>;
  // lodash
  public _: any = _;
  //判断是否已点击最新变更按钮
  public isChangeCheck = false;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  // 列表是否全选
  public isCheckedAll = false;
  // 列表数据
  public dataList: any;
  // 克隆列表新数据,用于页面数据标红对比
  public isChangeList: any = [];
  // 用于是否显示下拉框
  public isEditList: any = [];
  // 分页列表post
  public getBody: any = {
    pageIndex: 1,
    pageSize: 10,
    sFullName: '',
    sFundCode: '',
    sFundType: '',
    sStatus: [],
    dateTime: ''
  }
  // 公募列表分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  }
  // 用于判断是模态框查询还是页面查询
  public isQuery: any = false;
  // 阅读须知摘要内容
  public sTitle: any;
  // 用于显示、隐藏阅读须知摘要
  public isShowSummary: any = false;
  // 基金状态下拉框值
  public fundStatus: any = [];
  public fundList: any = [];

  constructor(
    public viewPageService: ViewPageService,
    public resolver: ComponentFactoryResolver,
    public investService: InvestService,
    public dataService: DataService
  ) {
    let that = this;
    // 用于触发搜索模态框查询
    this.investService.query = new EventEmitter();
    this.investService.query.subscribe((data: any) => {
      if (data == 'view') {
        that.isQuery = true;
        that.list();
      }
    })
  }

  ngOnInit() {
    let that = this;
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '投资范围指标') {
                _.forEach(it.children, (ite, i) => {
                  if (ite.sName == '指标查看') {
                    that.menuResourceSet = ite.resourceSet
                    sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
                  }
                })
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '投资范围指标') {
            _.forEach(it.children, (ite, i) => {
              if (ite.sName == '指标查看') {
                that.menuResourceSet = ite.resourceSet
                sessionStorage.setItem('btn-rcmi', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    // 加载table
    this.showViewTable();
    // 基金状态
    this.getFundStatus();
    this.list();
  }
  ngAfterViewInit() {

  }
  // 获取基金状态下拉框
  getFundStatus() {
    let that = this;
    this.viewPageService.getFundStatus().subscribe(data => {
      if (data) {
        that.fundList = data.subTree;
        localStorage.setItem("fundList", JSON.stringify(that.fundList));
      }
    })
  }
  // 基金状态下拉框赋值
  setFundStatus(fundType: any) {
    let that = this;
    if (fundType == '') {
      that.getBody.sStatus = [];
      window['$']('#viewFundStatus').selectpicker('destroy');
    } else {
      _.forEach(this.fundList, item => {
        if (item.sFundType == fundType) {
          that.getBody.sStatus = [];
          setTimeout(function () {
            window['$']('#viewFundStatus').selectpicker('destroy');
            Util.loadSelect(item.subTree, 'viewFundStatus');
          }, 1);
        }
      })
    }
  }
  //最新变更数据
  newChangeInfo() {
    if (this.isChangeCheck) {
      delete this.getBody.type;
      this.list();
    } else {
      this.getBody['type'] = 1;
      this.list();
    }
    this.isChangeCheck = !this.isChangeCheck;
  }
  // 分页列表
  list(pageNum?, pageSize?) {
    let that = this;
    let postBody: any;
    this.isCheckedAll = false;
    if (this.isQuery) {
      // 去除勾选、清空页面查询条件
      this.getBody.sFullName = '';
      this.getBody.sFundCode = '';
      this.getBody.sFundType = '';
      this.getBody.sStatus = [];
      this.getBody.dateTime = '';
      // 查询条件非空转码
      _.forIn(this.investService.queryBody, (value, key) => {
        if (key == 'sStatus' || key == 'nFundNo') {
          // 基金状态下拉框不做处理
        } else {
          that.investService.queryBody[key] = _.trim(that.investService.queryBody[key]);
        }
      })
      // 去除公用的在途查询条件
      delete this.investService.queryBody.type;
      postBody = _.cloneDeep(this.investService.queryBody);
    } else {
      this.getBody.sFullName = _.trim(this.getBody.sFullName);
      this.getBody.sFundCode = _.trim(this.getBody.sFundCode);
      postBody = _.cloneDeep(this.getBody);
    }
    postBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    postBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.activeTab(postBody.sFundType);
    new Promise((resolve, reject) => {
      this.viewPageService.list(postBody).subscribe(data => {
        if (data) {
          that.dataList = data.list;
          that.listPageInfo.currentPageNum = data.pageNum;
          that.listPageInfo.totalPages = data.pages;
          that.listPageInfo.total = data.total;
          that.listPageInfo.startRow = data.startRow;
          that.listPageInfo.endRow = data.endRow;
          // 用于标红对比
          that.isChangeList = _.cloneDeep(data.list);
          // 用于是否显示下拉框
          that.isEditList = _.cloneDeep(that.dataList);
          _.forEach(that.isChangeList, item => {
            // 将所有赋false,查看页面不需要标红
            _.forIn(item, (value, key) => {
              item[key] = false;
            })
          })
          _.forEach(that.isEditList, item => {
            // 将所有赋'no',查看页面不需要显示下拉框
            _.forIn(item, (value, key) => {
              item[key] = 'no';
            })
          })
          resolve(resolve);
        }
      })
    }).then(resolve => {
      that.viewTableComponent.instance.isCheckedAll = false;
      that.viewTableComponent.instance.dataList = _.cloneDeep(that.dataList);
      that.viewTableComponent.instance.isChangeList = _.cloneDeep(that.isChangeList);
      that.viewTableComponent.instance.isEditList = _.cloneDeep(that.isEditList);
    })
  }
  // 分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.list(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  // 获取列表数据
  getList(index: any) {
    if (index == '8') {
      this.isQuery = false;
      this.showTargetViewRead(index);
    } else {
      this.getBody.sFundType = index;
      this.isQuery = false;
      this.setFundStatus(index);
      this.list();
    }
  }
  // 显示模版
  showModel(type) {
    let that = this;
    let checkedItem = [];
    _.forEach(this.viewTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item);
      }
    });
    if (checkedItem.length == 1) {
      switch (type) {
        case 'view':
          this.showView(checkedItem);
          break;
        case 'flow':
          this.showFlow(checkedItem[0]);
          break;
        case 'single':
          this.showSingle(checkedItem[0]);
          break;
      }
    } else if (checkedItem.length < 1) {
      window['swal']("提示", "请选择一条记录!", "warning");
    } else if (checkedItem.length > 1) {
      window['swal']("提示", "只能选择一条记录!", "warning");
    }
  }
  // 搜索模版
  showQuery() {
    if (this.queryComponent && this.queryComponent.instance) {
      this.queryComponent.destroy();
    }
    const queryComponent = this.resolver.resolveComponentFactory(QueryComponent);
    this.queryComponent = this.query.createComponent(queryComponent);
    this.queryComponent.instance.type = 'view';
    window['$']('#query').modal('show');
  }
  // 查看模版
  showView(dataList) {
    if (this.viewComponent && this.viewComponent.instance) {
      this.viewComponent.destroy();
    }
    const viewComponent = this.resolver.resolveComponentFactory(ViewComponent);
    this.viewComponent = this.view.createComponent(viewComponent);
    this.viewComponent.instance.dataList = _.cloneDeep(dataList);
    this.viewComponent.instance.type = 'view';
    window['$']('#view').modal('show');
  }
  // 查看流程状态模版
  showFlow(item) {
    if (this.flowComponent && this.flowComponent.instance) {
      this.flowComponent.destroy();
    }
    const flowComponent = this.resolver.resolveComponentFactory(FlowComponent);
    this.flowComponent = this.flow.createComponent(flowComponent);
    this.flowComponent.instance.getFlowBody.nIjId = item.nIjId;
    this.flowComponent.instance.getFlowBody.nIxId = item.nFundNo;
    this.flowComponent.instance.getFlowBody.nFlowId = item.nFlowId;
    this.flowComponent.instance.getBody.nIjId = item.nIjId;
    this.flowComponent.instance.getBody.nIxId = item.nFundNo;
    this.flowComponent.instance.getBody.nFlowId = item.nFlowId;
    this.flowComponent.instance.type = 'view';
    window['$']('#viewTargetFlow').modal('show');
  }
  // 查看单条基金变更模版
  showSingle(item) {
    if (this.singleComponent && this.singleComponent.instance) {
      this.singleComponent.destroy();
    }
    const singleComponent = this.resolver.resolveComponentFactory(SingleComponent);
    this.singleComponent = this.single.createComponent(singleComponent);
    this.singleComponent.instance.getBody.nIxId = item.nIxId;
    this.singleComponent.instance.type = 'view';
    window['$']('#single').modal('show');
  }
  // 查看历史变更
  historyChange() {
    let that = this;
    let nFundNolist = [];
    _.forEach(this.viewTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        nFundNolist.push(item.nFundNo);
      }
    });
    if (nFundNolist.length == 0) {
      this.showHistory('');
    } else {
      let nFundNolists = nFundNolist.join(",");
      this.showHistory(nFundNolists);
    }
  }
  // 查看历史变更模版
  showHistory(item) {
    if (this.historyComponent && this.historyComponent.instance) {
      this.historyComponent.destroy();
    }
    const historyComponent = this.resolver.resolveComponentFactory(HistoryComponent);
    this.historyComponent = this.history.createComponent(historyComponent);
    this.historyComponent.instance.getBody.nIxIds = item;
    this.historyComponent.instance.type = 'view';
    window['$']('#history').modal('show');
  }
  // 阅读须知模版
  showTargetViewRead(index) {
    this.activeTab(index);
    if (this.viewReadPageComponent && this.viewReadPageComponent.instance) {
      this.viewReadPageComponent.destroy();
    }
    const viewReadPageComponent = this.resolver.resolveComponentFactory(ViewReadPageComponent);
    this.viewReadPageComponent = this.viewReadPage.createComponent(viewReadPageComponent);
  }
  // 模版
  showViewTable() {
    if (this.viewTableComponent && this.viewTableComponent.instance) {
      this.viewTableComponent.destroy();
    }
    const viewTableComponent = this.resolver.resolveComponentFactory(TableComponent);
    this.viewTableComponent = this.viewTable.createComponent(viewTableComponent);
    this.viewTableComponent.instance.isShowCol1 = 'sFundTypeZh';
    this.viewTableComponent.instance.isShowCol2 = 'viewsFullName';
    this.viewTableComponent.instance.isShowCol3 = 'sStatus';
  }
  // 获取阅读须知摘要
  getSummary() {
    let that = this;
    this.viewPageService.getSummary().subscribe(data => {
      that.sTitle = data.sTitle;
    })
  }
  // 阅读须知摘要
  showSummary(operate: any) {
    let that = this;
    switch (operate) {
      case 'show':
        that.getSummary();
        that.isShowSummary = true;
        break;
      case 'hide':
        that.isShowSummary = false;
        break;
    }
  }
  // 导出指标
  exportTarget() {
    let that = this;
    let checkedItem = [];
    let postBody: any;
    _.forEach(this.viewTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nFundNo);
      }
    })
    // 请求body
    if (this.isQuery) {
      postBody = _.cloneDeep(this.investService.queryBody);
      postBody['nFundNo'] = checkedItem;
      delete postBody.pageIndex;
      delete postBody.pageSize;
    } else {
      postBody = {
        "nFundNo": checkedItem,
        "sFullName": this.getBody.sFullName,
        "sFundCode": this.getBody.sFundCode,
        "sFundType": this.getBody.sFundType,
        "sStatus": this.getBody.sStatus,
        "dateTime": this.getBody.dateTime
      }
    }
    // 请求Url
    let postUrl = environment.server + '/pms/v1/riskmanage/investData/exportInvestData?token=' + sessionStorage.getItem('token');
    // 导出指标
    this.viewPageService.exportTarget(postUrl, postBody, '导出指标');
  }
  // 导出历史明细
  exportHistory() {
    let that = this;
    let checkedItem = [];
    _.forEach(this.viewTableComponent.instance.dataList, item => {
      if (item.isChecked) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem = checkedItem.join(',');
    let getBody: any = {
      'nIxIds': converItem
    }
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    //  转码，兼容ie
    getBody.sFullName = encodeURI(getBody.sFullName)
    iframe.attr('src', environment.server + '/pms/v1/riskmanage/investData/exportHistoryJournal?token=' + sessionStorage.getItem('token') + '&nIxIds=' + getBody.nIxIds);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  // 激活tab
  activeTab(sFundType: any) {
    window['$']('#view-ALL').removeClass('active');
    window['$']('#view-GM').removeClass('active');
    window['$']('#view-YDD').removeClass('active');
    window['$']('#view-YDY').removeClass('active');
    window['$']('#view-QYNJ').removeClass('active');
    window['$']('#view-YLJ').removeClass('active');
    window['$']('#view-SB').removeClass('active');
    window['$']('#view-YLJJ').removeClass('active');
    window['$']('#tab1').removeClass('active');
    window['$']('#view-READ').removeClass('active');
    window['$']('#tab2').removeClass('active');
    switch (sFundType) {
      case '':
        window['$']('#view-ALL').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '1':
        window['$']('#view-GM').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '2':
        window['$']('#view-YDD').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '3':
        window['$']('#view-YDY').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '4':
        window['$']('#view-QYNJ').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '5':
        window['$']('#view-YLJ').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '6':
        window['$']('#view-SB').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '7':
        window['$']('#view-YLJJ').addClass('active');
        window['$']('#tab1').addClass('active');
        break;
      case '8':
        window['$']('#view-READ').addClass('active');
        window['$']('#tab2').addClass('active');
        break;
    }
  }

}
